<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="formRules" label-width="120px" size="medium">
      <el-form-item label="员工姓名" prop="userName">
        <el-input v-model="form.userName" style="width:300px" />
      </el-form-item>
      <el-form-item label="员工工号" prop="jobNumber">
        <el-input v-model.trim="form.jobNumber" style="width:300px" />
      </el-form-item>
      <el-form-item label="岗位类别" prop="jobCategory">
        <el-input v-model.trim="form.jobCategory" disabled style="width:300px" />
      </el-form-item>
      <el-form-item label="隶属工段" prop="sectionNo">
        <el-input v-model="form.sectionNo" style="width:300px" />
      </el-form-item>
      <el-form-item label="员工角色" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择该员工当前角色" @focus="getRole" style="width:300px">
          <el-option :value="item.roleId" :label="item.roleName" v-for="(item,index) of this.roleList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="员工短号">
        <el-input v-model="form.shortNum" style="width:300px" />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="form.phone" maxlength="11" style="width:300px" />
      </el-form-item>
      <el-form-item label="隶属部门" prop="departmentName">
        <el-select v-model="form.departmentName" placeholder="请选择该员工当前所在部门" @focus="getDepart" @change="form.sectionType = ''" style="width:300px">
          <el-option :value="item" :label="item" v-for="(item,index) in this.departList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="组别" prop="sectionType" v-if="form.departmentName && this.isNeedget(this.form.departmentName)">
        <el-select v-model="form.sectionType" placeholder="组别" @focus="getsectionType" style="width:300px" @change="changesectionType">
          <el-option :value="item" :label="item" v-for="(item,index) in this.sectionTypeList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所在岗位" prop="jobTitle">
        <el-select v-model="form.jobTitle" placeholder="请选择所在岗位" @focus="getjobTitle" style="width:300px" @change="changeJobTitle">
          <el-option :value="item.id" :label="item.jobTitle" v-for="(item,index) in this.jobTitleList" :key="index"/>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="工种类型" prop="type" required v-if="form.departmentName == '数控车间'">
        <el-select v-model="form.type" placeholder="请选择该员工工种类型" style="width:300px">
          <el-option :value="item" :label="item" v-for="(item,index) of this.typeList" :key="index"/>
        </el-select>
      </el-form-item> -->
      <el-form-item label="上级领导工号" prop="parentNumber">
        <el-input v-model="form.parentNumber"  @blur="testExist2()" style="width:300px" />
      </el-form-item>
      <el-form-item label="入职时间" prop="entryTime">
        <el-date-picker v-model="form.entryTime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width:300px" />
      </el-form-item>
      <el-form-item label="员工岗位职级" prop="jobClassStr">
        <el-cascader v-model="form.jobClassStr" separator="-" :options="options" clearable style="width:300px"/>
      </el-form-item>
      <el-form-item label="技能等级" prop="skillRank">
        <el-cascader v-model="form.skillRank" :options="optionsRank" clearable style="width:300px"/>
      </el-form-item>
      <el-form-item label="岗位技能" prop="jobTitle">
          <div v-for="(items,index1) in trainObjList" :key="index1" style="margin-bottom: 5px;">
            <el-select filterable disabled @focus="getjobTitle" v-model="items.jobTitle" placeholder="请选择" style="width:150px; margin-right: 20px;">
              <el-option
              v-for="(item,index) in jobTitleList"
              :key="index"
              :label="item.jobTitle"
              :value="item.id">
            </el-option>
          </el-select>
          <!-- <el-form-item label="技能等级"> -->
            {{' 技能等级 '}}
            <el-input v-model="items.rankOfPosition" disabled style="width:100px;margin-left: 10px;" />
          <!-- </el-form-item> -->
          <!-- <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delPost(index1)"></el-button>
          <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addPost"></el-button> -->
        </div>
      </el-form-item>
       <el-form-item label="邮箱" prop="mail">
        <el-input v-model="form.mail" style="width:300px" />
      </el-form-item>
      <el-form-item label="导师" prop="tutorJobNumber">
        <el-select filterable clearable v-model="form.tutorJobNumber" placeholder="请选择导师" @focus="focusName" style="width:300px">
          <el-option :value="item.userName" :label="item.userName" v-for="(item,index) of this.nameList" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="新员工标识" prop="newEmployee">
        <el-switch v-model="form.newEmployee" active-value="1" inactive-value="0" active-text="新员工" inactive-text="老员工" />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用" inactive-text="停用" />
      </el-form-item>
      <el-form-item label="员工头像上传" required>
        <el-upload
          class="avatar-uploader"
          action="https://www.golwayhhln.top/hnsMes/portraitUploadFile"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :data="upPictureData"
          :headers="upPictureHeader"
          :before-upload="beforeAvatarUpload">
          <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  @click="submitForm('form')">提交</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import { addWorker,testWorkNum } from '@/api/user'
import { checkWorkSecInfo } from '@/api/workSection.js'
import { knowledgeFind } from '@/api/knowledgeSkill.js'
import mixin from '@/utils/mixin.js'
// import { validatePhone, validateChineseName, validateNum} from '@/utils/validate'
import { getRoleInfo, getDepartInfo } from '@/utils/publicFun'
export default {
 name: 'addUser_List',
 mixins: [mixin],
 data() {
    return {
      form: {
        userName: '',                               //员工姓名
        roleId: '',                                 //员工角色
        jobNumber: '',                              //员工工号
        shortNum: '',                               //员工短号
        jobClassStr: '',                            //员工岗位职级数组
        parentNumber: '',                           //上级领导工号
        phone: '',                                  //员工手机号码
        departmentName: '',                         //员工隶属部门
        entryTime: '',                              //员工入职时间
        status: '1',                                //员工启用状态
        imageUrl: '',                               //员工头像URL地址
        newEmployee: false,                         //新员工标识
        sectionNo: '',                                 //隶属工段
        type: '',
        sectionType: '',
        mail:'',               //邮箱
      },
      formRules: {
        userName: [
            { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        sectionNo: [
            { required: true, message: '请输入工段编号', trigger: 'blur' }
        ],
        jobNumber: [
            { required: true, message: '请输入员工工号', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择员工角色', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请选择员工隶属部门', trigger: 'blur' }
        ],
        sectionType: [
          { required: true, message: '组别不能为空', trigger: 'blur' }
        ],
        parentNumber: [
          { required: true, message: '请选择改员工上级领导工号', trigger: 'blur' }
        ],
        jobClassStr: [
          { required: true, message: '请选择员工职级', trigger: 'blur' }
        ],
        skillRank: [
          { required: true, message: '技能等级不能为空', trigger: 'blur' }
        ],
        entryTime: [
          { required: true, message: '请选择员工入职时间', trigger: 'blur' }
        ],
        mail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
      },
      departList: [],                                           // 从后台部门信息放在该对象中
      roleList: [],                                             // 从服务器调取员工角色信息放入该对象当中
      upPictureHeader: {
        CHECK_USER_VALUE: 'GOLWAY',
        CHECK_PASSWORD_VALUE: '8D4DD3F80CEB6149329FDBD590B164F1'
      },                                                        // 员工头像上传的请求头部
      upPictureData: {file: '' },                               //员工头像上传时附带的额外参数
      // 岗位职级下拉选项信息
      options: [{
        value: 'O1',
        label: 'O1',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O2',
        label: 'O2',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O3',
        label: 'O3',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      },  {
        value: 'O4',
        label: 'O4',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }, {
        value: 'O5',
        label: 'O5',
        children: [{
          value: '1',
          label: '1'
        }, {
          value: '2',
          label: '2'
        }, {
          value: '3',
          label: '3'
        }, {
          value: '4',
          label: '4'
        }, {
          value: '5',
          label: '5'
        }]
      }],
      optionsRank: [
        {
        value: 'T0',
        label: 'T0',
        },
        {
        value: 'T1',
        label: 'T1',
        },
        {
        value: 'T2',
        label: 'T2',
        },
        {
        value: 'T3',
        label: 'T3',
        },
        {
        value: 'T4',
        label: 'T4',
        },
        {
        value: 'T5',
        label: 'T5',
        }
      ],
      // 工种类型
      typeList: [
        '数冲',
        '折弯',
        '钳铆'
      ],
      sectionTypeObj: {
        emsOrz: [],
        cnc: ['数控一组','数控二组','铜排组','试制组','医疗产品组','职员组'],
        weld: ['人工焊组','机器人组','打磨组','职员组'],
        spray:['喷涂一线','喷涂二线','喷涂三线','样品线','前处理组','辅助组','职员组'],
        SheetMetal:['装配一线','装配二线','装配三线','装配四线','装配五线','装配六线','装配七线','装配八线','装配九线','包装组','组件一线','组件二线','组件三线','附件组','职员组'],
      },
      sectionTypeList: [],
      // 有组级的部门
      isNeedList: ['EMS总装车间','装配车间','数控车间','焊接车间','结构总装车间','总装车间','销售服务部','研发部','喷涂车间','钣金装配','QC部','钣金工程部','钣金工艺部','新产品验证部','电装QC部','EMS车间','电装工艺部',
      '华海车间','物流部','PMC部','质量管理部','人力资源部','财务部'],
      marketList:['合同管理部','深圳销售一部','销售二部1组','销售二部2组','销售二部3组'],
      researchList:['深圳研发中心','从化研发中心'],
      QCList:['IPQC组','FQC组','职员组'],
      sheetMetal:['工程组','编程组'],
      metalProcess:['制程工艺组','装配工艺组'],
      productVerification:['NPI组','制程工艺组','职员组'],
      electricQC:['华海质量部','MES质量部','职员组'],
      technology:['华海工艺部','MES工艺部','职员组'],
      MESplant:['整机一线','整机二线','整机三线','插框线','包装线','充电桩专线','职员组'],
      HHplant:['整机线','插框线','附件组','包装组','职员组'],
      logistics:['ZA华为组','ZA发货组','木工组','原材料组','ZB共管组','ZB原材料组'],
      PMC:['计划组','物控组'],
      qualityControl:['质量保证部','供应商质量部','流程体系部'],
      HR:['信息安全部','绩效薪酬部','行政安全部','招聘任职部','深圳招聘任职部'],
      finance:['从化财务组','深圳财务组'],
      jobTitleList:[],
      trainObjList:[{jobTitle:''}],
    }
  },
  methods: {
    // 添加培训对象
    addPost(){
        this.trainObjList.push({jobTitle:''})
      },
    // 删除培训对象
    delPost(index){
        if(this.trainObjList.length == 1){
          this.trainObjList = [{jobTitle:''}]
        } else {
          this.trainObjList.splice(index, 1);
        }
      },
      // 岗位技能发生改变
      objChang(e,index1){
        console.log('e',e)
          if(e){
            this.jobTitleList.forEach(item =>{
              if(item.id == e){
                this.trainObjList[index1].id = item.id
                this.trainObjList[index1].jobTitle = item.jobTitle
                item.rankOfPosition == 1 ? this.trainObjList[index1].rankOfPosition = '试用级' 
                :item.rankOfPosition == 2 ? this.trainObjList[index1].rankOfPosition = '初级'
                :item.rankOfPosition == 3 ? this.trainObjList[index1].rankOfPosition = '中级'
                :item.rankOfPosition == 4 ? this.trainObjList[index1].rankOfPosition = '高级'
                :item.rankOfPosition == 5 ? this.trainObjList[index1].rankOfPosition = '师傅级':''
                // this.trainObjList[index1].rankOfPosition = item.rankOfPosition
              }
            })
          }
      },
    // 获取岗位
    async getjobTitle(){
      const res = await knowledgeFind({page:1,  limit:10000})
      this.jobTitleList = res.data.list
    },
    // 岗位改变
    changeJobTitle(e){
      console.log(e)
      this.jobTitleList.forEach(item =>{
        if(item.id == e){
          this.form.jobCategory = item.jobCategory
          this.form.userKnowledgePostId  = item.id
          this.trainObjList[0].id = item.id
          this.trainObjList[0].jobTitle = item.jobTitle
          item.rankOfPosition == 1 ? this.trainObjList[0].rankOfPosition = '试用级' 
          :item.rankOfPosition == 2 ? this.trainObjList[0].rankOfPosition = '初级'
          :item.rankOfPosition == 3 ? this.trainObjList[0].rankOfPosition = '中级'
          :item.rankOfPosition == 4 ? this.trainObjList[0].rankOfPosition = '高级'
          :item.rankOfPosition == 5 ? this.trainObjList[0].rankOfPosition = '师傅级':''
        }
    })
    },
    // 将当前输入的工号传递到后台系统，验证改工号是否已经被注册
    async testExist2() {
      const data = await testWorkNum({ jobNumber: this.form.parentNumber, type: '1' })
      if(data.code == '1'){
          this.$message({
            type: 'success',
            message: '工号验证通过'
          })
      } else {
          this.$message({
            type: 'warning',
            message: data.msg
        })
      }
    },
    // 获取角色列表函数,当选择器框获得焦点时触发,从服务器调取参数
    async getRole() {
      const res = await getRoleInfo()
      this.roleList = res
    },
    changesectionType(e){
      this.$set(this.form, 'sectionType', e)
    },
    // 获取部门函数
    async getDepart() {
      const res = await getDepartInfo()
      this.departList = res
    },
    isNeedget(val){
      return this.isNeedList.some(item => item == val.trim())
    },
    getsectionType(){
      if(this.form.departmentName.trim() == 'EMS总装车间' || this.form.departmentName.trim() == '装配车间' || this.form.departmentName.trim() == '总装车间' || this.form.departmentName.trim() == '结构总装车间') {
        let workCenter = this.form.departmentName.trim() == '结构总装车间'?'总装车间':this.form.departmentName.trim()
        this.getworkSection(workCenter)
      } else if(this.form.departmentName.trim() == '数控车间') {
        this.sectionTypeList = this.sectionTypeObj.cnc
      } else if(this.form.departmentName.trim() == '焊接车间') {
        this.sectionTypeList = this.sectionTypeObj.weld
      } else if(this.form.departmentName.trim() == '喷涂车间') {
        this.sectionTypeList = this.sectionTypeObj.spray
      } else if(this.form.departmentName.trim() == '钣金装配') {
        this.sectionTypeList = this.sectionTypeObj.SheetMetal
      } else if(this.form.departmentName.trim() == '销售服务部') {
        this.sectionTypeList = this.marketList
      } else if(this.form.departmentName.trim() == '研发部') {
        this.sectionTypeList = this.researchList
      } else if(this.form.departmentName.trim() == 'QC部') {
        this.sectionTypeList = this.QCList
      } else if(this.form.departmentName.trim() == '钣金工程部') {
        this.sectionTypeList = this.sheetMetal
      } else if(this.form.departmentName.trim() == '钣金工艺部') {
        this.sectionTypeList = this.metalProcess
      } else if(this.form.departmentName.trim() == '新产品验证部') {
        this.sectionTypeList = this.productVerification
      } else if(this.form.departmentName.trim() == '电装QC部') {
        this.sectionTypeList = this.electricQC
      } else if(this.form.departmentName.trim() == 'EMS车间') {
        this.sectionTypeList = this.MESplant
      } else if(this.form.departmentName.trim() == '电装工艺部') {
        this.sectionTypeList = this.technology
      } else if(this.form.departmentName.trim() == '华海车间') {
        this.sectionTypeList = this.HHplant
      } else if(this.form.departmentName.trim() == '物流部') {
        this.sectionTypeList = this.logistics
      } else if(this.form.departmentName.trim() == 'PMC部') {
        this.sectionTypeList = this.PMC
      } else if(this.form.departmentName.trim() == '质量管理部') {
        this.sectionTypeList = this.qualityControl
      } else if(this.form.departmentName.trim() == '人力资源部') {
        this.sectionTypeList = this.HR
      } else if(this.form.departmentName.trim() == '财务部') {
        this.sectionTypeList = this.finance
      }
    },
    async getworkSection(val){
      let midsectionTypeList = []
      const { data } = await checkWorkSecInfo({workCenter: val,page: 1,limit: 10000})
      data.records.forEach(item => {
        if(item.status && item.sectionAbbreviation){ midsectionTypeList.push(item.sectionAbbreviation) }
      });
      if(!midsectionTypeList.length) return this.sectionTypeList = []
      let set = new Set(midsectionTypeList)
      this.sectionTypeList = Array.from(set)
      this.sectionTypeList.push('附件组')
    },
    // 提交表单之前先进行验证
    submitForm(formName) {
      // if(this.form.departmentName == '数控车间' && !this.form.type) return  this.$message({
      //     type: 'warning',
      //     message: '请选择该员工工种类型'
      // })

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.onSubmit()
        } else {
          return false
        }
      })
    },
    // "提交"按钮绑定函数，将用户填写的表单form提交
    // 在提交之前将jobClassStr数组拼接为字符串
    async onSubmit() {
      const res2 = await testWorkNum({ jobNumber: this.form.parentNumber, type: '1' })
      if(res2.code != '1'){
          return this.$message({
            type: 'warning',
            message: '上级领导工号不存在！'  
        })
      }
      if(!this.trainObjList[this.trainObjList.length-1].jobTitle) return this.$message.error('岗位技能最后一个不能为空！')
      let query = Object.assign({},this.form)
      let arr1 = []
      this.trainObjList.forEach(item => {
          arr1.push(item.id)
      })  
      query.userKnowledgePostIdStr = arr1.join(',')
      query.jobClassStr = query.jobClassStr.join('-')
      if(this.form.departmentName == '数控车间'){
          query.type = this.form.type == '数冲'?1:
                       this.form.type == '折弯'?2:
                       this.form.type == '钳铆'?3:0
      } else {
          query.type = 0
      }
      if(!query.sectionType) { delete query.sectionType }
      query.skillRank = this.form.skillRank.toString()
      const data = await addWorker(query)
      const errMsg = data.msg
      if(data.code=='1'){
            this.$message({
              type: 'success ',
              message: errMsg
          })
      } else {
            this.$message({
              type: 'warning',
              message: errMsg
        })
      }
    },
    // "取消"按钮
    onCancel() {
      console.log('bye')
    },
    // 用户头像上传成功之后的触发函数
    // 将服务器上的头像URL地址赋值给this.form.imageUrl，从而在表单上显示该图片
    handleAvatarSuccess(res) {
      this.form.imageUrl = res.results
	  if(res.code == '1') {
		  this.$message({
		    message: '上传成功',
		    type: 'success'
		  })
	  } else {
		  this.$message({
		    message: '上传失败',
		    type: 'error'
		  })
	  }
    },
    // 用户头像上传之前判断函数，格式限制为JPG，大小小于2M
    // const声明一个只读的常量。一旦声明，常量的值就不能改变。且只在声明所在的块级作用域内有效
    // 判断图像的大小与格式，传递true或false,后面的if语句进行判断
    async beforeAvatarUpload(file) {
      this.upPictureData.file = file
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>